package com.jookes.signplugin.shop;

import net.milkbowl.vault.economy.Economy;

import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.plugin.RegisteredServiceProvider;

import com.jookes.signplugin.main.Main;

public class ShopHandler {

	public static Economy economy = null;
	private Main plugin;
	
	public ShopHandler(Main plugin){
		this.plugin = plugin;
		this.setupEconomy();
	}
	@SuppressWarnings("deprecation")
	public void buyItem(Player player, int amount, String material, double price) {
		
		Double balance = economy.getBalance(player.getName());
		Material mat = Material.matchMaterial(material);
		PlayerInventory inventory = player.getInventory();
		
		if(mat != null)
		{
			if(balance > price){
				
				//Withdraw the money
				economy.bankWithdraw(player.getName(), price);
				
				//Create a stack of the given amount.
				ItemStack stack = new ItemStack(mat, amount);
				inventory.addItem(stack);
				player.updateInventory();
				player.sendMessage(ChatColor.RED + "$"+ price + " Has been taken from your account");
			}else{
				player.sendMessage(ChatColor.RED + "You don't have enough money");
			}
		}
		
		
	}

	public void sellItem(Player player, int amount, String material, double price) {
		economy.bankDeposit(player.getName(), price);
		player.sendMessage(ChatColor.GREEN + "$"+price+ " Has been added to your account");
	}

	private boolean setupEconomy() {
		RegisteredServiceProvider<Economy> economyProvider = plugin.getServer()
				.getServicesManager()
				.getRegistration(net.milkbowl.vault.economy.Economy.class);
		if (economyProvider != null) {
			economy = economyProvider.getProvider();
		}

		return (economy != null);
	}
}
